import React from 'react';
import { asyncComponent } from 'react-async-component';
import { Route, withRouter, Switch, Redirect } from 'react-router-dom';
import Create from '../create/index';
import {inject, observer} from 'mobx-react';
import { TabPage, routeBackToUpperlevel } from 'weaver-mobile-page';
import {Tools, Icon} from 'weaver-mobile';
const getLabel = Tools.getLabel;
const coms = {
  index: asyncComponent({
    resolve: () => import("../base/index")
  }),
  discussData: asyncComponent({
    resolve: () => import("../base/discussData")
  }),

}
// @routeBackToUpperlevel
@inject('viewWorkplanStore')
@inject('createStore')
@withRouter
@observer
class Detail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowTab:0,
      isDiscuss:false
    };
  }

  componentWillMount() {
    let { setParams } = this.props.viewWorkplanStore;
    let pathstr = window.location.hash && window.location.hash.split('#');
    this.setPage(pathstr[1]);
    const pathName = this.props.location.pathname
    const URL = this.props.location.search ? this.props.location.search.split('?')[1] : ''
    const url = URL.length > 0 ? URL.split('&') : [];
    const Arr = this.getQuery(url);
    if(Arr['fromType']){
      setParams({fromType:Arr['fromType']})
    }else{
      setParams({fromType:''})
    }
  }
  componentDidMount() {
    /* 查看时支持route的两种形式： 
      1, /detail?workplanId=** 
      2, route.push({pathname: /detail, query{workplanId: **}})
    */
    let { changeWorkplanID,setParams ,initWorkPlan} = this.props.viewWorkplanStore;
    initWorkPlan();
    // const workplanId = this.props.location.search ? this.props.location.search.split('=')[1]:(this.props.location&&this.props.location.query&&this.props.location.query.workplanId)
    // setParams({workplanid:workplanId})
    
    const URL = this.props.location.search ? this.props.location.search.split('?')[1] : ''
    const url = URL.length > 0 ? URL.split('&') : [];
    const Arr = this.getQuery(url);
    let workplanId = this.props.location.search ? Arr['workplanId'] : this.props.location&&this.props.location.query&&this.props.location.query.workplanId;
    let isfromchatshare = this.props.location.search ? Arr['isfromchatshare'] : this.props.location&&this.props.location.query&&this.props.location.query.isfromchatshare;
    let isfromMessageCenter = this.props.location.search ? Arr['isfromMessageCenter'] : this.props.location&&this.props.location.query&&this.props.location.query.isfromMessageCenter;
    let sharer = this.props.location.search ? Arr['sharer'] : this.props.location&&this.props.location.query&&this.props.location.query.sharer;
    let isDiscuss = this.props.location.search ? Arr['isDiscuss'] : this.props.location&&this.props.location.query&&this.props.location.query.isDiscuss;
    let fromType = this.props.location.search ? Arr['fromType'] : this.props.location&&this.props.location.query&&this.props.location.query.fromType;
    setParams({workplanid: workplanId,isfromchatshare:isfromchatshare,sharer:sharer,isDiscuss:isDiscuss,fromtype: fromType,isfromMessageCenter:isfromMessageCenter, isSingelViewWorkplan: true})
    localStorage.setItem('singleDetail',true);
    localStorage.setItem('workid',parseInt(workplanId,10).toString());
    if(localStorage) {
      localStorage.workid && changeWorkplanID(localStorage.workid);
    }
    if(isDiscuss === 1 || isDiscuss === '1') {
      this.setState({isDiscuss: true,nowTab:1})
    }
    if(this.props.location) { 
      const { search, pathname } = this.props.location;
      if(search.indexOf('fromCreate=true') > -1) {// 从新建后到查看页面
        this.props.history.push('/detail/index');
        setParams({ isSingleHasWorkplanId: true });
      } else {
        if(workplanId !== undefined) { // 单页查看有workplanid
          setParams({ isSingleHasWorkplanId: true });
        }
      }

      if(pathname.indexOf('discussData') > -1 || String(isDiscuss) === '1') {
        this.props.history.push(`/detail/discussData${search}`);
      } else {
        this.props.history.push(`/detail/index${search}`);
      }
    }
  }

  getQuery = (search)=>{
    let params ={}
    search.map((v,index)=>{
      const tempV = v.split('=');
      params[tempV[0]] = tempV[1];
      return '';
    });
    return params
  }

  componentWillReceiveProps (nextProps) {
    const { location:{pathname}  } = this.props;
    const { history: h,location:{pathname:p, search: nSearch} } = nextProps;
    let { isfromMessageCenter, fromType } = this.props.viewWorkplanStore;
    if(window.em) {
      if(h && h.action === 'POP'){
        //从消息中心/微搜/客户/项目都能点进来,并且都是detail/index和detail/discussData
        const path = ['/detail/discussData','/detail/index', '/detail/create']
        if(p != pathname && path.indexOf(p)>-1 && path.indexOf(pathname)>-1
          || nSearch.indexOf('fromCreate=true') > -1   // 从新建后到查看页面
        ){
          if( fromType !== 'crm') {
            window.em.closeWindow();
          }
        }
        if(nextProps.location && nextProps.location.pathname === '/detail') {
          window.em.closeWindow();
        }
      }
    }  else {
      if(nextProps.location && nextProps.location.pathname === '/detail') {
        this.props.history.go(-1);
      }
    }

  }

  shouldComponentUpdate(preProps) {
    let { otherModuleCloseWP } = this.props.viewWorkplanStore;
    if(otherModuleCloseWP){
      const { location: { pathname: preP }, history: h } = preProps;
      const { location: { pathname: p } } = this.props;
  
      const reg = /\/[^\\/]+$/;
      if (preP !== p && preP.replace(reg, '') === p.replace(reg, '') && h.action === 'POP') {
        h.go(-1);
        return false;
      }
    }
    
    return true;
  }
  
  componentWillUnmount() {
    localStorage.removeItem('singleDetail');
    localStorage.removeItem('workid');
  }

  setPage = (path) => {
    if (path.indexOf('detail/index') > -1) { this.setState({ nowTab: 0 }); }
    if (path.indexOf('detail/discussData') > -1) {this.setState({ nowTab: 1 }); }
  }
   // 点击tab页切换
   changeTab = (tab,index) => {
    const { search } = this.props.location;
    switch(tab.key) {
      case 1: this.setPath(index, `/detail/index${search}`); this.setState({ nowTab: 0 }); break;
      case 2: this.setPath(index, `/detail/discussData${search}`); this.setState({ nowTab: 1 }); break;
      default: ;
    }
  }

  setPath = (key, path) => {
    this.props.history.push(path);
  }

  render() {
    const { noRight, noSecretRight, noData } = this.props.viewWorkplanStore;
    const { isEdit } = this.props.createStore
    let redirectPathName = '/detail/index'
    let tabs = [];
    let workplanid = '';
    if(this.state.isDiscuss){
      redirectPathName = '/detail/discussData'
    }
    if(localStorage && localStorage.workid) {
      workplanid = localStorage.workid;
    }
    if(noRight) {
      tabs = [];
    }else{
      if(workplanid && workplanid.split('R') > 1 && !isEdit) {
        tabs.push(
          { title: getLabel(387394,'详细信息'),key:1 },
          { title: getLabel(15153,'相关交流'),key:2 }
        )
      }else if(isEdit){
        tabs.push({ title: getLabel(387394,'详细信息'),key:1 })
      }else{
        tabs.push({ title: getLabel(387394,'详细信息'),key:1 })
      }
    }
    const tabProps = {
      onChange: (tab,index) => { this.changeTab(tab,index) },
      page: this.state.nowTab
    };
    return (
      <div className={'single-detail'}>
        {noRight?<div className='no-right'>
          <div className='icon-noright'>
            <Icon type='wuquanxian' size='lg'/>
          </div>
          <div className='message'>
            {getLabel(2012,'对不起，您暂时没有权限！')}
          </div>
        </div>:noData?<div className='no-right'>
          <div className='icon-noright'>
            <Icon type='wuquanxian' size='lg'/>
          </div>
          <div className='message'>
            {getLabel(508094,'该日程已被删除！')}
          </div>
        </div>:noSecretRight?<div className='no-right'>
          <div className='icon-noright'>
            <Icon type='wuquanxian' size='lg'/>
          </div>
          <div className='message'>
            {getLabel(501082 ,'对不起，您的人员密级不足以查看该内容')}
          </div>
        </div>:<TabPage
          tabs={tabs}
          tabProps={tabProps}
        />
      }
          {!noRight&&!noData&&!noSecretRight&&<div className={'single-detail-content'}>
            <Switch>
              <Route
                key="index"
                path="/detail/index"
                component={coms.index}
              />
              <Route
                key="discussData"
                path="/detail/discussData"
                component={coms.discussData}
              />
               <Route
                key="edit"
                path={'/detail/create'}
                render={()=>(
                  <div id="edit">
                    <Create />
                  </div>
                )}
              />
              {/* <Redirect  exact path="/detail"  to={{pathname: redirectPathName}} /> */}
            </Switch>
          </div>}
      </div>
    );
  }
}

export default Detail;